import datetime

import webapp2

from google.appengine.ext import db

HOMEPAGE_HTML_HEAD = """<!DOCTYPE html>
<html><head><title>Brisbane ATC - ISAC 2013</title><meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="/static/style.css" /></head>
<body><h1>High scores!</h1><ol>"""
HOMEPAGE_HTML_TAIL = """</ol></body></html>"""

def stringify_delta(delta):
    times = [
            ('minute', 60),
            ('hour', 60 * 60),
            ('day', 60 * 60 * 24),
            ('month', 60 * 60 * 24 * 30),
            ('year', 60 * 60 * 24 * 366)
    ]
    s = delta.total_seconds()
    unit = None
    amount = None
    for name, seconds in times:
        if s >= 2 * seconds:
            amount = s / seconds
            unit = name
            break
    if unit is None:
        unit = 'second'
        amount = s
    amount = int(amount)
    return '{0} {1} ago'.format(amount, unit if amount == 1 else unit + 's')

class HighScore(db.Model):
    name = db.StringProperty()
    time = db.DateTimeProperty()
    score = db.IntegerProperty()
    seed = db.IntegerProperty()

class HomeHandler(webapp2.RequestHandler):
    def get(self):
        top = db.GqlQuery("SELECT * FROM HighScore ORDER BY score DESC LIMIT 10")
        self.response.headers['Content-type'] = 'text/html'
        self.response.write(HOMEPAGE_HTML_HEAD)
        for score in top:
            time_ago = stringify_delta(datetime.datetime.now() - score.time)
            self.response.write('<li>{0} got {1} points {2} with a the seed "{3}"</li>'
                    .format(score.name, score.score, time_ago, score.seed)
            )
        self.response.write(HOMEPAGE_HTML_TAIL)

    def post(self):
        #XXX there is no rate limiting/authentication/verification here
        data = {name: self.request.get(name) for name in ['name', 'score', 'seed']}
        time = datetime.datetime.now()
        s = HighScore()
        s.time = time
        s.name = data['name']
        s.score = int(data['score'])
        s.seed = int(data['seed'])
        s.put()
        self.response.write('OK')

app = webapp2.WSGIApplication([('/', HomeHandler)])
